package cn.poka.util;

import android.app.Activity;
import android.content.Context;

import java.util.ArrayList;
import java.util.List;

import cn.poka.device.RFIDDevice;
import cn.poka.device.WirelessDevice;

public class PokaContext {

	/** PokaContext实例 */
	protected static PokaContext instance;

	/** 所有activity集合 */
	protected List<Activity> activityList;

	/** 上下文环境 */
	protected Context context;

	protected PokaContext(Context context) {
		this.context = context;
	}

	public static void init(Context context) {
		instance = new PokaContext(context);
	}

	public static PokaContext getInstance() {
		return instance;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * 注册Activity
	 * @param activity
	 */
	public void pushActivity(Activity activity) {
		if (activityList == null) {
			activityList = new ArrayList<Activity>();
		}
		if (!activityList.contains(activity)) {
			activityList.add(activity);
		}
	}

	/**
	 * 移除一个Activity
	 * @param activity
	 * @return
	 */
	public Boolean removeActivity(Activity activity) {
		Boolean result = Boolean.FALSE;
		if (activityList != null) {
			result = activityList.remove(activity);
		}
		return result;
	}

	/**
	 * 获取一个Activity
	 * @return
	 */
	public Activity popActivity() {
		if (activityList != null && activityList.size() > 0) {
			return activityList.remove(activityList.size() - 1);
		}
		return null;
	}

	/**
	 * 关闭所有Activity
	 */
	public void finishAllActivity() {
		Activity activity;
		while((activity = popActivity()) != null) {
			activity.finish();
		}
	}

	/**
	 * 关闭设备
	 */
	private void closeDevice(){
		//关闭RFID设备
		RFIDDevice.getInstance().close();

		//关闭无线串口设备
		WirelessDevice.getInstance().close();

		//关闭蜂鸣器
		//BeepDevice.getInstance().disenable();
		//BeepDevice.getInstance().close();

//		FingerDevice.getInstance().quit();
//		try {
//			Thread.sleep(10);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		FingerDevice.getInstance().disenable();
//		FingerDevice.getInstance().close();
//
//		Tools.fingerCount = 0;

	}

	/**
	 * 退出应用程序
	 */
	public void Exit(){
		closeDevice();

		finishAllActivity();
	}

}
